﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="virtualearth.aspx.cs" Inherits="CSP.CRM.ISVExtensions.VirtualEarthPage" %>


<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title><%=csp.GetConfigText("VirtualEarthTitle")%></title>

  <script type="text/javascript" src="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6"></script>

  <style type="text/css">
    html
    {
      overflow: hidden;
    }
    body
    {
      margin: 0px;
      padding: 0px;
      overflow: hidden;
    }
  </style>

  <script type="text/jscript">
          var selectedValues;
          var resultset;
          if (window.dialogArguments != null)
            selectedValues = window.dialogArguments;
          else
            selectedValues = new Array();
          var sGUIDValues = "";
          
          var map = null;
          var control = null;

          var layer_ok = null;
          var layer_happy = null;
          var layer_angry = null;
          var layer_pending = null;

          var labCaseDetails, labContactDetails, labSeeDetails;
          var labLayerSelector, labSatisfiedCitizens, labNeutralCitizens, labDisatisfiedCitizens, labUnratedCases; 
          
</script>
<%= LocalizeUserInterface() %> 
<script type="text/jscript">                  
          var pinid = 0;
          var infoboxOld = "<div style='width:309px;'><p><b>Contact details</b><br/>{contact_details}</p><p><b>Case details</b><br/>{case_details}</p><br>"
                        + "<a href='{details_url}' target='_blank'>Click here to see the case details.</a></div>";
                        
          var infobox = "<div style='width:309px;'><p><b>" + labContactDetails + "</b><br/>{contact_details}</p><p><b>" + labCaseDetails + 
          "</b><br/>{case_details}</p><br>" +
           "<a href='{details_url}' target='_blank'>" + labSeeDetails + "</a></div>";
                        
          var messageLabel;


          function trace(text)
          {
            if (messageLabel)
              messageLabel.innerText += text;          
          }

          function window.onload()
          {
             messageLabel = document.getElementById("lbMessage");
             if (selectedValues == "" || selectedValues.length == 0)
             {
                alert("You must select records in order to use this feature.");
                window.close();
             }
             else
                window.setTimeout(postCaseIds, 100);
          }
         
         function postCaseIds()
         {
          var selectedRecords = "<records>" + selectedValues.toString() + "</records>";
          
          var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
          xmlhttp.open("POST", window.location + "&pb=1", false);
          xmlhttp.send(selectedRecords);

          resultset = new ActiveXObject("Microsoft.XMLDOM");
          resultset.async = false;

          // Extract any XML message returned in the Http response and load
          // it into the XML document. <resultset/> tag is used to indicate
          // the end of the response message from the code-behind page.
          var eom = xmlhttp.responseText.indexOf("</resultset>") + 12;
          var xmlMessage = xmlhttp.responseText.substring(0, eom);

          resultset.loadXML(xmlMessage);          

          // If errors were returned in the Http response, display them.
          var oNodeError = resultset.selectSingleNode("error");
          if(oNodeError != null)
              trace(oNodeError.text);
          else
              DrawMap();
        }
        
        
        function SetBestMap()
        {
          var locs = new Array;
          var minLat = 90, maxLat = -90, minLong = 180, maxLong = -180;
          var results = resultset.getElementsByTagName('result');
          for (i = 0; i < results.length; i++)
          {
            var latitude = GetChildText(results[i], "contactid.address1_latitude");
            var longitude = GetChildText(results[i], "contactid.address1_longitude");
            if ((latitude == '?') || (longitude == '?'))
              continue;
            latitude = parseFloat(latitude);
            longitude = parseFloat(longitude);
            var loc = new VELatLong(latitude, longitude);
            locs.push(loc);
          }
          map.SetMapView(locs);
        }


      	function DrawMap()
        {
          try {
           map = new VEMap('myMap');
           map.LoadMap();
           SetBestMap();
           if (map.GetZoomLevel() > 12)
            map.SetZoomLevel(12);
           map.ClearInfoBoxStyles();
           layer_ok = new VEShapeLayer();
           map.AddShapeLayer(layer_ok);
           layer_happy = new VEShapeLayer();
           map.AddShapeLayer(layer_happy);
           layer_angry = new VEShapeLayer();
           map.AddShapeLayer(layer_angry);
           layer_pending = new VEShapeLayer();
           map.AddShapeLayer(layer_pending);
           map.ShowMiniMap();
           AddMyControl(); 
           RealignMiniMap();
           var results = resultset.getElementsByTagName('result');
           for (i = 0; i < results.length; i++)
            ProcessResult(results[i]);
         }
         catch (Exception)
         {
           trace("Error: " + Exception);
         }
       }
        
      function HideShowLayer(element)
      {
         if (!element.checked)
         {
            switch (element.id)
            {
               case '_ok': layer_ok.Hide();
                           break;
               case '_happy': layer_happy.Hide();
                           break;
               case '_angry': layer_angry.Hide();
                           break;
               case '_pending':
               default: layer_pending.Hide();
                           break;
            }
         }
         else
         {
            switch (element.id)
            {
               case '_ok': layer_ok.Show();
                           break;
               case '_happy': layer_happy.Show();
                           break;
               case '_angry': layer_angry.Show();
                           break;
               case '_pending':
               default: layer_pending.Show();
                           break;
            }
         }
      }

         
        function AddMyControl()
        {
           if (control == null) 
           {
              control = document.createElement('div');
              control.id = "myControl";
              control.style.position ="absolute";
              control.style.top ="280px";
              control.style.padding ="5px";
              control.style.width ="150px";
              control.style.fontFamily ="Arial";
              control.style.fontSize ="10px";
              control.style.left = "0px";
              control.style.border = "1px solid #cccccc";
              control.style.background = "#fefefe";
              control.innerHTML = "<table width='100%' style='border:1px solid #cccccc;font: 11px Arial;' id='tbLegend'><tr><td colspan='2' style='background-color:black; color:white; font-weight:bold;height:20px;' align='center'>" + 
                labLayerSelector + "</td></tr><tr><td>" + 
                labSatisfiedCitizens + "</td><td><input type='checkbox' checked='true' onclick='parent.HideShowLayer(this)' id='_happy'</td></tr><tr><td>" + 
                labNeutralCitizens + "</td><td><input type='checkbox' checked='true' onclick='parent.HideShowLayer(this)' id='_ok'</td></tr><tr><td>" + 
                labDisatisfiedCitizens + "</td><td><input type='checkbox' checked='true' onclick='parent.HideShowLayer(this)' id='_angry'</td></tr><tr><td>" +
                labUnratedCases + "</td><td><input type='checkbox' checked='true' onclick='parent.HideShowLayer(this)' id='_pending'</td></tr></table>";
              map.AddControl(control);
              addShim(control);
           }

        }
                
        function addShim(el)
        {
           var shim = document.createElement("iframe");
           shim.id = "myShim"; 
           shim.frameBorder = "0";
           shim.style.position = "absolute";
           shim.style.zIndex = "1";
           shim.style.top  = el.offsetTop;
           shim.style.left = el.offsetLeft;
           shim.width  = el.offsetWidth;
           shim.height = el.offsetHeight;
           el.shimElement = shim;
           el.parentNode.insertBefore(shim, el);

        }

        var MiniMapSize = VEMiniMapSize.Small; // can also be set to VEMiniMapSize.Large 

        function MapResize(e)
        {
            // When the map is resized, Realign the position of the Mini Map
            RealignMiniMap();
        } 

        function GetMapWidth()
        {   
            // Get the Width of the Map as an integer
            return document.getElementById("myMap").offsetWidth;
        }
        function GetMapHeight()
        {
            // Get the Height of the Map as an integer
            return document.getElementById("myMap").offsetHeight;
        }

        function RealignMiniMap()
        {
            // Realign the position of the Mini Map so it appears
            // where we want it - The Upper Right Corner
            var minimap = document.getElementById("MSVE_minimap");
            var xoffset = (GetMapWidth() - minimap.offsetWidth);
            map.ShowMiniMap(0, 130, MiniMapSize);
            
            /// Hide the Mini Map resizer so the Mini Map cannot be resized
            document.getElementById("MSVE_minimap_resize").style.display = "none";
        } 


        function GetChildText(node, childname)
        {
          var childNode = node.getElementsByTagName(childname)[0];
          if (childNode != null)
            return childNode.text;
          else 
            return '?';
        }

        function GetChildAttribute(node, childname, attributename)
        {
          var childNode = node.getElementsByTagName(childname)[0];
          if (childNode)
          {
          var attribute = childNode.getAttribute(attributename);
          if (attribute)
            return attribute;
          else 
            return '?';
          }
          else
            return '?';
        }

        function ProcessResult(result)
        {
        var latitude = GetChildText(result, 'contactid.address1_latitude').toString();
        var longitude = GetChildText(result, 'contactid.address1_longitude').toString();
        
        if (latitude == '?')
          return;
        if (longitude == '?')
          return;
          

        var ref = GetChildText(result, 'ticketnumber');
        var proceduretype = GetChildAttribute(result, 'csp_proceduretype', 'name');
        var caseid = GetChildText(result, 'incidentid');
        var url = "/cs/cases/edit.aspx?id=" + caseid;
        var fullname = GetChildText(result, 'contactid.fullname');
        var address = GetChildText(result, 'contactid.address1_line1');
        var phone = GetChildText(result, 'contactid.telephone1');
        var email = GetChildText(result, 'contactid.emailaddress1');
        var contact = fullname + "<br/>" + address + "<br/>" + phone + "<br/>" + email;
        var satisfaction = GetChildText(result, 'customersatisfactioncode');
        var tsatisfaction = GetChildAttribute(result, 'customersatisfactioncode', 'name');
        
        if (satisfaction == '?')
        {
          satisfaction = "0";
          tsatisfaction = "?";
        }
        details = proceduretype + "<br/>" + tsatisfaction;
        
        AddCustomPushpin(latitude, longitude, ref, url, contact, details, satisfaction);
        }
        
        function AddCustomPushpin(latitude, longitude, ref, url, contact, details, satisfaction)
        {
           var icon;
           var latlon   = new VELatLong(latitude, longitude);
           shape = new VEShape(VEShapeType.Pushpin, latlon);
           shape.SetTitle("<h3>" + ref + "</h3>");
           var text = infobox.replace("{details_url}", url);
           text = text.replace("{contact_details}", contact);
           text = text.replace("{case_details}", details);
           shape.SetDescription(text);
           switch (satisfaction)
           {
              case "4":
              case "5":
                 icon = "<img src='push-pin-green_transp.gif' width='25'/>";
                 shape.SetCustomIcon(icon);
                 layer_happy.AddShape(shape);
                 break;
              case "3":
                 icon = "<img src='push-pin-orange_transp.gif' width='25'/>";
                 shape.SetCustomIcon(icon);
                 layer_ok.AddShape(shape);
                 break;
              case "2":
              case "1":
                 icon = "<img src='push-pin-red_transp.gif' width='25'/>";
                 shape.SetCustomIcon(icon);
                 layer_angry.AddShape(shape);
                 break;
              case "0":
              default:
                 icon = "<img src='push-pin-unknown.gif' width='25'/>";
                 shape.SetCustomIcon(icon);
                 layer_pending.AddShape(shape);
                 break;
           }
        }


  </script>

    
</head>
<body>
    <form id="frmMain" runat="server">
    <!-- div id="lbMessage"></div -->
    <div id='myMap' style='position: absolute; width: 100%; height: 100%;'></div>
    </form>
</body>
</html>